#!/bin/bash
usage()
{
cat << EOF

$0 adds vlbistreamer commands to a snp-file. The output is a new snp-file with the name augmented to <snp>vbs.snp and a separate <snp>.recqueue script. The recqueue scripts can be run to queue the recording schedule to the vlbistreamer server.

If no host is given, the script will presume a vlbistreamer instance is running on localhost.

usage: $0 <snp-file> <options> <vbs_record options>

Options:
  -h <host> 	Prepare queue script for specific host
  -X 		Run queueing script after conversion.	

All extra options are added to each vbs_record command generated
EOF
}
#Go through params
VLBIHOST=ara.vlbi
VBS_QUEUE="vbs_queue -m r"
TMPSCANSFILE=$(mktemp)
TMPSTARTSFILE=$(mktemp)
TMPENDTIMES=$(mktemp)
EXTRAOPS=""
EXECUTE=0
n=1
while [ $# -gt 0 ]
do
  case $1 in
    -h) 
      VLBIHOST=$2
      REMOTER="ssh $VLBIHOST"
      shift
      ;;
    -X) 
      EXECUTE=1
      ;;
    -*)
      echo "Adding switch $1 to extra ops"
      EXTRAOPS="$EXTRAOPS $1"
      ;;
    *)
      #This could be nicer
      if [ "$(echo $1|cut -d '.' -f2)" == "snp" ]
      then
	echo "Target file $1"
	eval "arg_$n=$1";n=$(($n+1))
      else
	echo "Adding parameter $1 to extra ops"
	EXTRAOPS="$EXTRAOPS $1"
      fi
      ;;
    #-*) echo "Unknown argument $1";usage;exit 1; echo "Errors in parameters of streaming $RECNAME" >> $LOGFILE;;
esac
shift
done
if [ "$arg_1" == "" ]; then 
  usage
  exit -1
fi
SNP=$arg_1
if [ ! -z "$arg_2" ]; then
  #EXTRAOUT=`echo $SNP|sed 's/\(.*\)\.snp/\1\.vbs/'`
  EXTRAOUT=$arg_2
  echo "#!/bin/bash" > $EXTRAOUT
else
  EXTRAOUT=$arg_1".recqueue"
fi

#REMOTER="ssh $VLBIHOST"
I=1
#SNAMEVAR=scan_name

# get scan names, convert "," to space
#sed -n -e '/scan_name=/s/scan_name=//pj $SNP | sed -n -e 's/,/ /gp' > $TMPSCANSFILE
#sed '/scan_name=/s/scan_name=//p' $SNP  > $TMPSCANSFILE
grep 'scan_name=' $SNP | cut -d'=' -f2 > $TMPSCANSFILE

# get start times
# sed -n -e '/preob/,/!/p' $SNP | grep ! | sed -n -e 's/[!.]/ /gp' > ./starttimes
#cat $SNP | grep disk_pos -1 | grep ! | sed -n -e 's/[!.]/ /gp' > $TMPSTARTSFILE

#Clear old
cat /dev/null > $TMPSTARTSFILE

#LC=`wc -l $TMPSCANSFILE | awk '{print $1}'`
#I=0
#while [ $I -le $LC ]
while read line
do
  sed -n '/'$line'/,/data_valid=on/p' $SNP | tac |grep ! | head -n 1 |sed -e  's/[!.]/ /gp' |head -n1 >> $TMPSTARTSFILE
done < $TMPSCANSFILE

cat /dev/null > $TMPENDTIMES

while read line
do
  sed -n '/'$line'/,/data_valid=off/p' $SNP | tac |grep ! | head -n 1 |sed -e  's/[!.]/ /gp' |head -n1 >> $TMPENDTIMES
done < $TMPSCANSFILE

# get end times
#cat $SNP | grep data_valid=off -1 | grep ! | sed -n -e 's/[!.]/ /gp'|sed -n -e 's/[:.]/ /gp' > ./endtimes

#Now remove em commas.
sed -i 's/,/ /g' $TMPSCANSFILE

# get end times
#cat $SNP | grep data_valid=off -1 | grep ! | sed -n -e 's/[!.]/ /gp'|sed -n -e 's/[:.]/ /gp' > ./endtimes
#if [ ! -e $EXTRAOUT ]
#then
  echo "Emptying old file $EXTRAOUT"
  echo "#!/bin/bash" > $EXTRAOUT
#fi


#echo $SNP|sed 's/\(.*\)\.snp/\1vbs\.snp/'
NEWFILE=`echo $SNP|sed 's/\(.*\)\.snp/\1vbs\.snp/'`
#if [ -e $NEWFILE ]
#then
  #rm $NEWFILE
#fi
cp $SNP $NEWFILE

BIGBADA=""
UNCORKED=0
#if [ ! -z "$REMOTER" ]
#then
  #echo $REMOTER \" \\ >> $EXTRAOUT
#fi

I=1
LC=`wc -l $TMPSCANSFILE | awk '{print $1}'`
while [ $I -le $LC ]
do
  RARRAY=(`tail -n +$I $TMPSCANSFILE | head -1`)
  SARRAY=(`tail -n +$I $TMPSTARTSFILE | head -1`)
  EARRAY=(`tail -n +$I $TMPENDTIMES | head -1`)

  #AHSDG It seems date handles +016 days differently than +16days
  #valueWithoutZeroes="$(echo $valueWithZeroes | sed 's/0*//')"
  #SARRAY[0]=$(echo ${SARRAY[0]} | sed 's/0*//')
  SARRAY[1]=$(echo ${SARRAY[1]} | sed 's/0*//')
  #SARRAY[2]=$(echo ${SARRAY[2]} | sed 's/0*//')
  #EARRAY[0]=$(echo ${EARRAY[0]} | sed 's/0*//')
  EARRAY[1]=$(echo ${EARRAY[1]} | sed 's/0*//')
  #EARRAY[2]=$(echo ${EARRAY[2]} | sed 's/0*//')
  #echo ${SARRAY[@]} "EHERE" ${EARRAY[@]}
#Read more at http://www.askdavetaylor.com/how_do_i_strip_leading_zeroes_for_math_in_a_shell_script.html#LPkh75mIhLQLOp4A.99 

  #Use time from EPOCH as start time, since its nice to use in C
  #Aggh so +x days we need to negate one as we start from day 1
  STARTEPOCH=`date -u -d "01/01/${SARRAY[0]} + $((${SARRAY[1]}-1)) days ${SARRAY[2]}" +%s `
  ENDEPOCH=`date -u -d "01/01/${EARRAY[0]} + $((${EARRAY[1]} -1)) days ${EARRAY[2]}" +%s `
  #Duration is straight in the scan name.
  #Id wish!
  #dur=${RARRAY[4]}
  dur=$((ENDEPOCH - STARTEPOCH))
  #Trying to comform with http://vlbi.org/filename/
  EXPNAME=${RARRAY[1]}_${RARRAY[2]}_${RARRAY[0]}

  LINEOFSCAN=`grep "scan_name=${RARRAY[0]}" $NEWFILE -n| sed  's/\([0-9]*\).*/\1/'`
  #Adding $I to $LINEOFSCAN here because augmenting the file changes the
  #result each time. Don't know why thought..
  #sed -i "$LINEOFSCAN a sy=$REMOTER \"$VBS_QUEUE $EXPNAME $dur -e $STARTEPOCH\" $EXTRAOPS" $NEWFILE
  sed -i "$LINEOFSCAN a sy=$REMOTER \"$VBS_QUEUE $EXPNAME $dur $EXTRAOPS\"" $NEWFILE
  
  #echo $EXPNAME $STARTEPOCH $dur
  if [ "$((I % 4))" == "0" ]
  then
    DOTHEDOT="; printf \".\" ;"
  else
    DOTHEDOT=";"
  fi
  if [ ! -z "$REMOTER" ]
  then
    if [ "$UNCORKED" == "0" ]
    then
      UNCORKED=1
      BIGBADA="${VBS_QUEUE} $EXPNAME $dur -e $STARTEPOCH $EXTRAOPS $DOTHEDOT "
    else
      BIGBADA="$BIGBADA ; ${VBS_QUEUE} $EXPNAME $dur -e $STARTEPOCH $EXTRAOPS $DOTHEDOT "
    fi
    #echo "$REMOTER \"$VBS_QUEUE $EXPNAME $dur -e $STARTEPOCH\"">> $EXTRAOUT
    #echo \;${VBS_QUEUE} $EXPNAME $dur -e $STARTEPOCH\\>> $EXTRAOUT

  else
    echo $VBS_QUEUE $EXPNAME $dur -e $STARTEPOCH $EXTRAOPS $DOTHEDOT  >> $EXTRAOUT
  fi
  I=$(($I+1))
done
#done < starttimes

if [ ! -z "$REMOTER" ]
then
  #echo \" >> $EXTRAOUT
  echo $REMOTER \""$BIGBADA ; printf \"Done!\n\" \"" >> $EXTRAOUT
else
  echo "printf \"Done!\n\"" >> $EXTRAOUT
fi

chmod +x $EXTRAOUT

if [ "$EXECUTE" == "1" ]
then
  echo "Running scheduling script!"
  sh $EXTRAOUT
  if [ "$?" == "0" ]
  then
    rm $EXTRAOUT
  else
    echo "Error in running $EXTRAOUT!"
  fi
fi

rm $TMPSCANSFILE $TMPSTARTSFILE $TMPENDTIMES
